/*封装请求，同时支持jsonp和ajax*/
import axios from 'axios';
import jsonp from 'jsonp';
import { Modal } from 'antd';
import { stringifyObj } from "../util";

const BASE_URL = 'https://www.easy-mock.com/mock/5b8a10a878b10172ddd39a11/mockapi';
const TIME_OUT = 5000;

const request = ({ method = 'post', url = '', data = {}, headers = {}, param = 'callback' }) => {
  if (method === 'jsonp') {
    // 当method参数为jsonp时，发送jsonp请求
    return new Promise((resolve, reject) => {
      const stringifyData = stringifyObj(data);
      url = stringifyData ? `${url}?${stringifyData}` : url;
      jsonp(url, {
        param: param,
        timeout: TIME_OUT
      }, (err, res) => {
        if (res.status === 'success') {
          resolve(res.results[0]);
        } else {
          Modal.error({
            title: '提示',
            content: '请求出错，请稍后再试！'
          });
          reject(res.message)
        }
      })
    })
  }

  // 当method参数不是jsonp时，发送ajax请求
  return axios({
    method: method,
    url: url,
    data: data,
    params: data,
    baseURL: BASE_URL,
    headers: headers,
    timeout: TIME_OUT,
    transformRequest: [function (config) {
      // 按需要处理参数
      return config;
    }],

    transformResponse: [function (data) {
      // 按需要预处理data
      return data;
    }]
  }).then((res) => {
    let resData = JSON.parse(res.data);
    // 请求正确，返回数据
    if (resData.success) {
      return resData.data
    }
  }, (err) => {
    // ajax错误，弹出错误信息
    Modal.error({
      title: '提示',
      content: '请求出错，请稍后再试！'
    });
    return err;
  })
};

export default request
